import os
import shutil
from fastapi import APIRouter, Depends, File, UploadFile
from sqlalchemy.orm import Session
from typing import List

from api.database import get_db
from api.model.user import User
from api.model.email_account import EmailAccount
from api.model.draft import Draft
from api.controller.auth import get_current_user
from api.schemas.email.draft import EmailDraft, EmailDraftResponse
from api.schemas.response import ApiResponse
from api.utils.response import success, fail
from api.utils.logger import get_logger
from api.utils.async_helper import run_in_executor

logger = get_logger("drafts")

router = APIRouter()

@router.get("")
async def get_drafts(
    account_id: int,
    skip: int = 0,
    limit: int = 100,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取草稿列表
    """
    try:
        account = db.query(EmailAccount).filter(
            EmailAccount.id == account_id,
            EmailAccount.user_id == current_user.id
        ).first()
        if not account:
            return fail("邮箱账户未找到")

        query = db.query(Draft).filter(Draft.email_account_id == account_id)
        total = query.count()
        drafts = query.order_by(Draft.updated_at.desc()).offset(skip).limit(limit).all()
        
        # 草稿列表数据结构
        response_data = []
        for draft in drafts:
            # 计算附件数量 - 异步执行
            draft_dir = os.path.join("runtime", "files", "drafts", str(draft.id))
            attachment_count = 0
            
            def count_attachments():
                if os.path.exists(draft_dir):
                    return len([f for f in os.listdir(draft_dir) if os.path.isfile(os.path.join(draft_dir, f))])
                return 0
            
            attachment_count = await run_in_executor(count_attachments)
            
            response_data.append({
                "id": draft.id,
                "email_account_id": draft.email_account_id,
                "subject": draft.subject or "无主题",
                "recipients": draft.recipients or "",
                "cc": draft.cc or "",
                "attachment_count": attachment_count,
                "updated_at": draft.updated_at,
                "folder": "Drafts",
            })
        return success(response_data, count=total)
    except Exception as e:
        return fail(f"获取草稿列表失败: {str(e)}")

@router.get("/{draft_id}")
async def get_draft(
    account_id: int,
    draft_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取单封草稿详情
    """
    try:
        account = db.query(EmailAccount).filter(
            EmailAccount.id == account_id,
            EmailAccount.user_id == current_user.id
        ).first()
        if not account:
            return fail("邮箱账户未找到")
        
        draft = db.query(Draft).filter(
            Draft.id == draft_id,
            Draft.email_account_id == account_id
        ).first()
        
        if not draft:
            return fail("草稿未找到")
        
        return success(draft)
    except Exception as e:
        return fail(f"获取草稿详情失败: {str(e)}")

@router.post("")
async def save_draft(
    account_id: int,
    draft: EmailDraft,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    保存邮件草稿到 drafts 表（不包含附件，附件通过单独接口上传）
    """
    try:
        account = db.query(EmailAccount).filter(
            EmailAccount.id == account_id,
            EmailAccount.user_id == current_user.id
        ).first()
        if not account:
            return fail("邮箱账户未找到")

        # 对于新草稿，如果未填写收件人则不保存
        if not draft.id and not draft.recipients:
            logger.info("新草稿未填写收件人，拒绝保存")
            return fail("新草稿必须填写收件人")

        if draft.id:
            # 更新现有草稿
            db_draft = db.query(Draft).filter(
                Draft.id == draft.id,
                Draft.email_account_id == account_id
            ).first()
            if not db_draft:
                return fail("草稿未找到")
            
            update_data = draft.dict(exclude_unset=True)
            for key, value in update_data.items():
                setattr(db_draft, key, value)
            from api.utils.helpers import get_beijing_time
            db_draft.updated_at = get_beijing_time()
            
        else:
            # 创建新草稿
            db_draft = Draft(
                email_account_id=account_id,
                subject=draft.subject or "无主题",
                recipients=draft.recipients or "",
                cc=draft.cc or "",
                body=draft.body or ""
            )
            db.add(db_draft)

        db.commit()
        db.refresh(db_draft)
        
        return success(data={"id": db_draft.id}, msg="草稿保存成功")
    except Exception as e:
        db.rollback()
        return fail(f"保存草稿失败: {str(e)}")

@router.get("/{draft_id}/attachments")
async def get_draft_attachments(
    account_id: int,
    draft_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    获取草稿的附件列表
    """
    try:
        account = db.query(EmailAccount).filter(
            EmailAccount.id == account_id,
            EmailAccount.user_id == current_user.id
        ).first()
        if not account:
            return fail("邮箱账户未找到")
        
        draft = db.query(Draft).filter(
            Draft.id == draft_id,
            Draft.email_account_id == account_id
        ).first()
        if not draft:
            return fail("草稿未找到")
        
        # 获取草稿附件目录 - 异步执行
        draft_dir = os.path.join("runtime", "files", "drafts", str(draft_id))
        
        def list_attachments():
            if not os.path.exists(draft_dir):
                return []
            
            attachments = []
            for filename in os.listdir(draft_dir):
                file_path = os.path.join(draft_dir, filename)
                if os.path.isfile(file_path):
                    file_size = os.path.getsize(file_path)
                    attachments.append({
                        "filename": filename,
                        "size": file_size
                    })
            return attachments
        
        attachments = await run_in_executor(list_attachments)
        return success(data=attachments)
    except Exception as e:
        logger.error(f"获取草稿附件列表失败: {str(e)}")
        return fail(f"获取附件列表失败: {str(e)}")

@router.delete("/{draft_id}")
async def delete_draft(
    account_id: int,
    draft_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    删除草稿及其附件文件夹
    """
    try:
        account = db.query(EmailAccount).filter(
            EmailAccount.id == account_id,
            EmailAccount.user_id == current_user.id
        ).first()
        if not account:
            return fail("邮箱账户未找到")
        
        draft_to_delete = db.query(Draft).filter(
            Draft.id == draft_id,
            Draft.email_account_id == account_id
        ).first()
        
        if not draft_to_delete:
            return fail("草稿未找到")
        
        # 删除草稿附件文件夹 - 异步执行
        draft_dir = os.path.join("runtime", "files", "drafts", str(draft_id))
        
        def remove_draft_dir():
            if os.path.exists(draft_dir):
                try:
                    shutil.rmtree(draft_dir)
                    logger.info(f"已删除草稿 {draft_id} 的附件文件夹: {draft_dir}")
                except Exception as e:
                    logger.error(f"删除草稿附件文件夹失败: {str(e)}")
        
        await run_in_executor(remove_draft_dir)
        
        # 删除草稿记录
        db.delete(draft_to_delete)
        db.commit()
        return success(msg="草稿已删除")
    except Exception as e:
        db.rollback()
        return fail(f"删除草稿失败: {str(e)}")

@router.post("/permanent-delete")
async def permanent_delete_drafts(
    account_id: int,
    payload: dict,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """
    批量彻底删除草稿
    """
    draft_ids = payload.get('email_ids', [])
    
    if not draft_ids:
        return fail("未提供要删除的草稿ID")
    
    try:
        account = db.query(EmailAccount).filter(
            EmailAccount.id == account_id,
            EmailAccount.user_id == current_user.id
        ).first()
        if not account:
            return fail("邮箱账户未找到")
        
        drafts_to_delete = db.query(Draft).filter(
            Draft.id.in_(draft_ids),
            Draft.email_account_id == account_id
        ).all()
        
        if not drafts_to_delete:
            return fail("未找到要删除的草稿")
        
        logger.info(f"开始批量删除 {len(drafts_to_delete)} 个草稿")
        
        # 删除每个草稿及其附件文件夹
        for draft in drafts_to_delete:
            # 删除草稿附件文件夹 - 异步执行
            draft_dir = os.path.join("runtime", "files", "drafts", str(draft.id))
            
            def remove_dir():
                if os.path.exists(draft_dir):
                    try:
                        shutil.rmtree(draft_dir)
                        logger.info(f"已删除草稿 {draft.id} 的附件文件夹: {draft_dir}")
                    except Exception as e:
                        logger.error(f"删除草稿附件文件夹失败: {str(e)}")
            
            await run_in_executor(remove_dir)
            
            # 从数据库删除
            db.delete(draft)
        
        db.commit()
        return success(msg="选中的草稿已彻底删除")
        
    except Exception as e:
        logger.error(f"批量删除草稿出错: {str(e)}", exc_info=True)
        db.rollback()
        return fail(f"批量删除草稿时出错: {e}")
